package com.example.previewvideo;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import com.example.demo.R;
import com.example.previewvideo.util.AudioBuffer;
import com.example.previewvideo.util.VideoBuffer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * author : 浪
 * date :2024/9/14 14:56
 * desc:
 */
public class PrerecordActivity extends AppCompatActivity {
    private static final long PRE_RECORD_DURATION_MS = 10000; // 10 seconds

    private AudioBuffer audioBuffer = new AudioBuffer();
    private VideoBuffer videoBuffer = new VideoBuffer();
    private Handler handler = new Handler();
    private Runnable stopRecordingRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prerecord);

        Button btnStartRecording = findViewById(R.id.btnStartRecording);
        btnStartRecording.setOnClickListener(v -> startPreRecording());

        // Ensure you handle runtime permissions if needed
    }

    private void startPreRecording() {
        try {
            audioBuffer.startRecording(this);
            videoBuffer.startRecording();

            stopRecordingRunnable = () -> {
                audioBuffer.stopRecording();
                videoBuffer.stopRecording();
                // Save recorded data
                saveRecordedData();
            };

            // Schedule stop recording after PRE_RECORD_DURATION_MS
            handler.postDelayed(stopRecordingRunnable, PRE_RECORD_DURATION_MS);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void saveRecordedData() {
        byte[] audioData = audioBuffer.getRecordedData();
        byte[] videoData = videoBuffer.getRecordedData();

        // Save data to files or process it as needed

        try (FileOutputStream audioOutputStream = new FileOutputStream(new File(getExternalFilesDir(null), "pre_recorded_audio.3gp"));
             FileOutputStream videoOutputStream = new FileOutputStream(new File(getExternalFilesDir(null), "pre_recorded_video.mp4"))) {


            String absolutePath = getExternalFilesDir(null).getAbsolutePath();

            Log.i("saveRecordedData",absolutePath);
            audioOutputStream.write(audioData);
            videoOutputStream.write(videoData);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
